package middleware

import (
	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
	"go-demo/common/global"
	"go-demo/utils"
	"net/http"
	"strings"
)

func JWTMiddleware() gin.HandlerFunc {
	var jwtKey = []byte(global.App.Config.JwtConfig.Secret)
	return func(c *gin.Context) {
		tokenString := ExtractToken(c)
		if tokenString == "" {
			utils.Fail(c, http.StatusUnauthorized, "Authorization header is missing")
			c.Abort()
			return
		}

		claims := &jwt.MapClaims{}
		token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
			return jwtKey, nil
		})

		if err != nil || !token.Valid {
			utils.Fail(c, http.StatusUnauthorized, "Invalid token")
			c.Abort()
			return
		}
		// 将用户id记录在 context中方面得到当前登录用户
		c.Set("userid", (*claims)["userid"])
		c.Next()
	}
}

// ExtractToken 从请求头中获取token
func ExtractToken(c *gin.Context) string {
	bearerToken := c.GetHeader("Authorization")
	if len(strings.Split(bearerToken, " ")) == 2 {
		return strings.Split(bearerToken, " ")[1]
	}
	return ""
}
